package com.jerry.consumer.controller;

import com.jerry.common.bean.Order;
import com.jerry.common.bean.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 一旦调用服务方法失败并抛出了错误信息后，会自动调用
 * @HystrixCommand标注好的fallbackMethod调用类中的指定方法
 */
@RestController
@RequestMapping("/shop/order")
public class OrderController {

	@Value("${provider.orderUrl}")
	private String orderUrl;

	@Autowired
	private DiscoveryClient discoveryClient;
	@Autowired
	private RestTemplate restTemplate;

	//查询订单列表
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	public List<Order> getOrderList() {
		List<Order> orderList = restTemplate.getForObject(this.orderUrl+"/order/list",List.class);
		return orderList;
	}

	//根据订单号查询订单
	@GetMapping("/get/{orderNumber}")
	public Order getOrder(@PathVariable("orderNumber") String orderNumber) {
		return restTemplate.getForObject(this.orderUrl + "/order/get/" + orderNumber, Order.class);
	}

	//根据用户id查询订单列表
	@GetMapping("/getByUserId/{userId}")
	public List<Order> getOrderList(@PathVariable("userId") long userId) {
		return restTemplate.getForObject(this.orderUrl + "/order/getByUserId/" + userId, List.class);
	}

	//查询provider-user的实例信息
	@GetMapping("/userInstance")
	public List<ServiceInstance> userInstance() {
		return this.discoveryClient.getInstances("provider-user");
	}

}
